const fs = require('fs')
const path = require('path')
const ReadByLine = require('./readlines')
const liner = new ReadByLine('scripts/node/svgs')

const temp = 'scripts/node/temp/register.tpl'
const outFolder = 'scripts/node/out'

// noinspection DuplicatedCode
const nodes = {
}

for (let value in nodes) {
  // 准备文件夹
  const valueL = value[0].toLowerCase() + value.substring(1, value.length)
  const parentFolder = path.join(outFolder, valueL)
  if (!fs.existsSync(parentFolder)) {
    fs.mkdirSync(parentFolder)
  }

  let usage = []
  for (let i = 0; i < nodes[value].length; i++) {
    // 准备数据
    const node = nodes[value][i]
    const key = node.key
    const keyL = key[0].toLowerCase() + key.substring(1, key.length)
    const title = node.title
    const filename = node.file
    const start = `<symbol id="${node.icon}" viewBox="0 0 1024 1024">`

    let l
    while (l = liner.next()) {
      if (l.substring(0, start.length) === start) {
        // 格式化svg
        l = l.substring(start.length, l.indexOf('</symbol>'))
        let h = ''

        // 遍历获取path
        const paths = l.split('</path>')
        for (let j = 0; j < paths.length; j++) {
          if (paths[j].length > 0) {
            const d = paths[j].substring(paths[j].indexOf('d="') + 3, paths[j].length - 17)
            const fill = paths[j].substring(paths[j].indexOf('fill="') + 6, paths[j].length - 2)
            h +=
              `          h(
            'path',
            {
              fill: '${fill}',
              d: '${d}'
            }
          ),\n`
          }
        }

        // 生成文件
        h = h.substring(0, h.length - 2)
        let content = fs.readFileSync(temp, 'utf8')
        content = content.replace('${function}', keyL)
        content = content.replace('${h}', h)
        content = content.replace('${key}', key)
        content = content.replace('${title}', title)
        fs.writeFileSync(path.join(parentFolder, filename + '.js'), content)

        // 生成import文件
        usage.push({
          imports: `import ${keyL} from './${valueL}/${filename}'`,
          exec: `${keyL}(flow)`
        })
        liner.reset()
        break
      }
    }
  }

  const usagePath = path.join(parentFolder, 'imports.js')
  for (let i = 0; i < usage.length; i++) {
    fs.appendFileSync(usagePath, usage[i].imports)
    fs.appendFileSync(usagePath, '\n')
  }
  for (let i = 0; i < usage.length; i++) {
    fs.appendFileSync(usagePath, usage[i].exec)
    fs.appendFileSync(usagePath, '\n')
  }
}
